package com.wandian.news.mvvm.passthrough;

import android.os.Bundle;
import android.view.Gravity;
import android.view.View;

import androidx.databinding.DataBindingUtil;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.mylib.libcore.config.CoinTypeEnum;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.mvvm.BaseMVVMActivity;
import com.mylib.libcore.tools.CSJADTools;
import com.mylib.libcore.tools.GDTADTools;
import com.mylib.libcore.utils.ActivityUtil;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.wandian.news.R;
import com.wandian.news.bean.PassThroughBean;
import com.wandian.news.databinding.NewsActivityPassThroughBinding;
import com.wandian.news.dialog.CGFailedDialog;
import com.wandian.news.dialog.CGSuccessDialog;

import static com.mylib.libcore.config.AppConfig.CSJ_BANNER_ONE_ID;

/**
 * @author Administrator
 * @date 2019/12/18-14:28
 * @description 闯关activity
 **/
@Route(path = RouterConfig.ROUTER_ACTIVITY_NEWS_PASS_THROUGH)
public class PassThroughActivity extends BaseMVVMActivity<PassThroughActivityViewModel> implements CGFailedDialog.CGDialogBtnClink, CGSuccessDialog.CGDialogSuccessBtnClink {
    private NewsActivityPassThroughBinding dataBinding;
    private CGFailedDialog cGFailedDialog;
    private CGSuccessDialog cgSuccessDialog;
    private int answerSuccessNum = 0;//回答成功数
    private int nowGK = 1;//当前关卡
    private PassThroughBean bean;
    private int error_number = 1;
    private int challengeNumber = 0;
    @Override
    public void init(Bundle savedInstanceState) {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.news_activity_pass_through);
        dataBinding.setLifecycleOwner(this);
        dataBinding.setViewModel(mViewModel);
        Bundle bundle = getIntent().getExtras();
        if(!UIUtils.isEmpty(bundle)){
            try {
                nowGK = Integer.parseInt(bundle.getString("cg_num"))+1;
                challengeNumber= Integer.parseInt(bundle.getString("cg_times"));
            }catch (Exception e){}
        }
        initViewData();
        initClink();
        getViewData();
        UIUtils.setKeyEveryDayCoin(CoinTypeEnum.CG_COIN);
    }

    private void getViewData(){
        dataBinding.llError.setVisibility(View.GONE);
        if(challengeNumber>0){
            mViewModel.getData();
        }else {
            ToastUtil.show("今日闯关次数已上限");
            dataBinding.etAnswer.setVisibility(View.GONE);
            dataBinding.bindTransparentToolBar.toolBarTitleRight.setVisibility(View.GONE);
            dataBinding.tvSubmit.setVisibility(View.GONE);
        }

        //获取广告
        CSJADTools.loadCSJAdMiddleBanner(getContext(),dataBinding.rlAdBottom,"",CSJ_BANNER_ONE_ID,375,90);
        GDTADTools.loadHFAd(getContext(),dataBinding.flAdBottomGdt,375,0 );
    }

    private void initViewData(){
        ActivityUtil.getInstance().showStatusView(this,dataBinding.viewSysTop,true);
        dataBinding.tvAnswerNum.setText("1");
        dataBinding.bindTransparentToolBar.toolBarTitleRight.setVisibility(View.GONE);
        dataBinding.bindTransparentToolBar.toolBarTvTitle.setText("第"+nowGK+"关");
        dataBinding.bindTransparentToolBar.toolBarTitleRight.setText("放弃");
        dataBinding.bindTransparentToolBar.toolBarTitleRight.setVisibility(View.VISIBLE);

        dataBinding.tvChallengeNum.setText(challengeNumber+"");

        mViewModel.dataBean.observe(this,dataBean->{
            if(!UIUtils.isEmpty(dataBean)){
              this.bean = dataBean;
                dataBinding.bindTransparentToolBar.toolBarTitleRight.setVisibility(View.VISIBLE);
                dataBinding.etAnswer.setVisibility(View.VISIBLE);
                dataBinding.tvSubmit.setVisibility(View.VISIBLE);
                dataBinding.etAnswer.getText().clear();
                dataBinding.tvTitle.setText(dataBean.getQuest()+"");
            }
        });

        //更新挑战数据
        mViewModel.cBean.observe(this,cBean->{
            if(!UIUtils.isEmpty(cBean)){
                dataBinding.bindTransparentToolBar.toolBarTvTitle.setText("第"+cBean.getNum()+"关");
                dataBinding.tvChallengeNum.setText(cBean.getSurplusNum()+"");
                challengeNumber = cBean.getSurplusNum();
            }
        });
    }

    private void notifyAnswerSuccess(){
        answerSuccessNum = answerSuccessNum+1;
        if(answerSuccessNum>=7){
            passGK();
        }else {
            if(answerSuccessNum>=nowGK+1 && answerSuccessNum>0){
                passGK();
            }else {
                getViewData();
                dataBinding.etAnswer.getText().clear();
            }
        }
    }
    private void passGK(){
        nowGK = nowGK + 1;
        error_number = 1;
        mViewModel.notifyUserCG(0);
        dataBinding.bindTransparentToolBar.toolBarTitleRight.setVisibility(View.GONE);
        dataBinding.tvSubmit.setText("闯关成功，继续挑战");
        dataBinding.llError.setVisibility(View.GONE);
        showSuccessDialog();
    }

    private void initClink(){
        dataBinding.bindTransparentToolBar.toolBarTitleRight.setOnClickListener(v -> {
            if(UIUtils.isFastClick())return;
            showFailedDialog(bean.getAnswer()+"");
        });

        dataBinding.bindTransparentToolBar.toolBarIvBack.setOnClickListener(v -> {
            finishhideSoftBoard();
            finish();
        });
        dataBinding.tvSubmit.setOnClickListener(v -> {
            finishhideSoftBoard();
            if(dataBinding.tvSubmit.getText().toString().equals("闯关成功，继续挑战")){
                answerSuccessNum = 0;
                dataBinding.tvAnswerNum.setText("1");
                dataBinding.tvSubmit.setText("确定");
                getViewData();
            }else {
                if(UIUtils.isEmpty(dataBinding.etAnswer.getText())){
                    ToastUtil.show("请作答");
                    return;
                }
                String ed_text = dataBinding.etAnswer.getText().toString().trim()+"";
                if(ed_text.length()<=0){
                    ToastUtil.show("请作答");
                    return;
                }

                if(!UIUtils.isEmpty(bean) && !UIUtils.isEmpty(bean.getAnswer())){
                    if(bean.getAnswer().length()<=4){
                        if(bean.getAnswer().equals(ed_text)){
                            error_number =1;
                            dataBinding.llError.setVisibility(View.GONE);
                            ToastUtil.show("回答正确");
                            dataBinding.tvAnswerNum.setText(answerSuccessNum+1);
                            notifyAnswerSuccess();
                        }else {
                            dataBinding.llError.setVisibility(View.VISIBLE);
                            dataBinding.tvErrorNumber.setText("回答错误 x"+error_number);
                            dataBinding.tvErrorNumber.setTextSize(13f+error_number);
                            error_number++;
                        }
                    }else {
                        if(bean.getAnswer().contains(ed_text)){
                            error_number =1;
                            dataBinding.llError.setVisibility(View.GONE);
                            ToastUtil.show("回答正确");
                            dataBinding.tvAnswerNum.setText(answerSuccessNum+1);
                            notifyAnswerSuccess();
                        }else {
                            dataBinding.tvErrorNumber.setText("回答错误 x"+error_number);
                            dataBinding.tvErrorNumber.setTextSize(13f+error_number);
                            dataBinding.llError.setVisibility(View.VISIBLE);
                            error_number++;
                        }
                    }
                    if(error_number>5) showFailedDialog(bean.getAnswer()+"");
                }else {
                    ToastUtil.show("网络异常,请重新闯关");
                    finish();
                }
            }

        });

    }

    //展示失败弹框
    private void showFailedDialog(String answer){
        mViewModel.notifyUserCG(1);
        dataBinding.tvSubmit.setText("闯关失败，重新挑战");
        dataBinding.tvSubmit.setVisibility(View.GONE);
        dataBinding.etAnswer.setVisibility(View.GONE);
        dataBinding.bindTransparentToolBar.toolBarTitleRight.setVisibility(View.GONE);
        try {
            cGFailedDialog = new CGFailedDialog(getContext(),answer,this::viewBtnClink);
            //显示窗口
            //设置layout在PopupWindow中显示的位置
            if(!UIUtils.isEmpty(dataBinding.llTop)){
                cGFailedDialog.showAtLocation(dataBinding.llTop, Gravity.CENTER, 0, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //展示成功弹框
    private void showSuccessDialog( ){
        try {
            cgSuccessDialog = new CGSuccessDialog(getContext(),"",this::viewSuccessBtnClink);
            //显示窗口
            //设置layout在PopupWindow中显示的位置
            if(!UIUtils.isEmpty(dataBinding.llTop)){
                cgSuccessDialog.showAtLocation(dataBinding.llTop, Gravity.CENTER, 0, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        finishhideSoftBoard();
        super.onDestroy();
    }

    @Override
    public void viewBtnClink() {
        answerSuccessNum = 0;
        dataBinding.tvAnswerNum.setText("1");
        dataBinding.tvSubmit.setText("确定");
        getViewData();
    }

    @Override
    public void viewSuccessBtnClink() {
        answerSuccessNum = 0;
        dataBinding.tvAnswerNum.setText("1");
        dataBinding.tvSubmit.setText("确定");
        getViewData();
    }
}
